package com.rand.beauty;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;
import net.youmi.android.AdManager;
import net.youmi.android.diy.DiyManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.domob.android.ads.DomobAdEventListener;
import cn.domob.android.ads.DomobAdView;
import cn.domob.android.ads.DomobAdManager.ErrorCode;

import com.dodola.model.DuitangInfo;
import com.dodowaterfall.Helper;
import com.dodowaterfall.widget.ScaleImageView;
import com.example.android.bitmapfun.util.ImageCache;
import com.example.android.bitmapfun.util.ImageFetcher;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.umeng.analytics.MobclickAgent;

@SuppressLint("HandlerLeak")
public class PullToRefreshSampleActivity extends Activity implements
		IXListViewListener {
	private ImageFetcher mImageFetcher;
	private XListView mAdapterView = null;
	private StaggeredAdapter mAdapter = null;
	private int currentPage = 0;
	private DomobAdView mAdview320x50;
	public static final String PUBLISHER_ID = "56OJw0oouNI2Bb3sTp";
	public static final String FlexPID = "16TLuJHvApkyYNU-bmLwlFzk";
	private LinkedList<DuitangInfo> mInfos;
	final private String mUrlPrefix = "http://xiangce.baidu.com";
	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mHandler;
	private final int UPDATE_TEXT = 1;
	private int mSelectedClass = 0;

	@SuppressLint("UseSparseArrays")
	private HashMap<Integer, Integer> mReadTmp = new HashMap<Integer, Integer>();

	final String mMenus[] = { "推荐", "性感", "诱惑", "写真", "气质", "模特", "日韩美女", "清纯",
			"小清新", "校花" };

	final String mUrls[] = { "/square/282847", "/square/290527",
			"/square/290015", "/square/283103", "/square/290783",
			"/square/263903", "/square/50623967", "/square/270303",
			"/square/267999", "/square/311775" };

	ContentTask task = new ContentTask(this, 2);

	private class ContentTask extends
			AsyncTask<String, Integer, List<DuitangInfo>> {

		private Context mContext;
		private int mType = 1;

		public ContentTask(Context context, int type) {
			super();
			mContext = context;
			mType = type;
		}

		@Override
		protected List<DuitangInfo> doInBackground(String... params) {
			try {
				return parseNewsJSON(params[0]);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<DuitangInfo> result) {
			if (mType == 1) {
				mAdapter.addItemTop(result);
				mAdapter.notifyDataSetChanged();
				mAdapterView.stopRefresh();

			} else if (mType == 2) {
				mAdapterView.stopLoadMore();
				mAdapter.addItemLast(result);
				mAdapter.notifyDataSetChanged();
			}

		}

		@Override
		protected void onPreExecute() {
		}

		public List<DuitangInfo> parseNewsJSON(String url) throws IOException {
			List<DuitangInfo> duitangs = new ArrayList<DuitangInfo>();
			String json = "";
			if (Helper.checkConnection(mContext)) {
				try {
					json = Helper.getStringFromUrl(url);

				} catch (IOException e) {
					Log.e("IOException is : ", e.toString());
					e.printStackTrace();
					return duitangs;
				}
			}
			Log.d("MainActiivty", "json:" + json);

			try {
				JSONObject jsonObject = new JSONObject(json)
						.getJSONObject("data");
				JSONArray jsonArray = jsonObject.getJSONArray("album_list");
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject _json = (JSONObject) jsonArray.opt(i);
					String ablum = _json.getString("album_name");
					String pic = _json.getString("pic_name");
					String pic_url = _json.getJSONObject("small").getString(
							"pic_small_src");
					String pic_sign = _json.getString("pic_sign");

					if (!KeyFilterUtils.isCanShow(ablum)
							|| !KeyFilterUtils.isCanShow(pic)) {
						continue;
					}

					DuitangInfo newsInfo1 = new DuitangInfo();
					newsInfo1.setMsg(pic);
					newsInfo1.setAlbid(ablum);
					newsInfo1.setIsrc(pic_url);
					newsInfo1.setHeight(230);
					newsInfo1.setSign(pic_sign);
					duitangs.add(newsInfo1);
					mImageFetcher.startLoadImageForBack(pic_url);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return duitangs;
		}
	}

	/**
	 * 娣诲姞鍐呭
	 * 
	 * @param pageindex
	 * @param type
	 *            1涓轰笅鎷夊埛鏂�2涓哄姞杞芥洿澶�
	 */
	private void AddItemToContainer(int pageindex, int type) {
		if (task.getStatus() != Status.RUNNING) {
			String url = mUrlPrefix + mUrls[mSelectedClass] + "?" + "pn="
					+ pageindex + "&type=json";

			mReadTmp.put(mSelectedClass, pageindex);

			Log.d("MainActivity", "current url:" + url);
			ContentTask task = new ContentTask(this, type);
			task.execute(url);

		}
	}

	public class StaggeredAdapter extends BaseAdapter {
		public StaggeredAdapter(Context context, XListView xListView) {
			mInfos = new LinkedList<DuitangInfo>();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			DuitangInfo duitangInfo = mInfos.get(position);

			if (convertView == null) {
				LayoutInflater layoutInflator = LayoutInflater.from(parent
						.getContext());
				convertView = layoutInflator.inflate(R.layout.infos_list, null);
				holder = new ViewHolder();
				holder.imageView = (ScaleImageView) convertView
						.findViewById(R.id.news_pic);
				holder.contentView = (TextView) convertView
						.findViewById(R.id.news_title);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();
			holder.imageView.setImageWidth(duitangInfo.getWidth());
			holder.imageView.setImageHeight(duitangInfo.getHeight());
			holder.contentView.setText(duitangInfo.getAlbid() + ":\r\n"
					+ duitangInfo.getMsg());
			mImageFetcher.loadImage(duitangInfo.getIsrc(), holder.imageView);
			return convertView;
		}

		class ViewHolder {
			ScaleImageView imageView;
			TextView contentView;
			TextView timeView;
		}

		@Override
		public int getCount() {
			return mInfos.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mInfos.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public void addItemLast(List<DuitangInfo> datas) {
			mInfos.addAll(datas);
		}

		public void addItemTop(List<DuitangInfo> datas) {
			for (DuitangInfo info : datas) {
				mInfos.addFirst(info);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_pull_to_refresh_sample);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.titlebtn);
		((Button) findViewById(R.id.back_btn)).setVisibility(View.INVISIBLE);

	//	CookieSyncManager.createInstance(getApplicationContext());
		//CookieManager.getInstance().removeAllCookie();
		
		mAdapterView = (XListView) findViewById(R.id.list);
		mAdapterView.setPullLoadEnable(true);
		mAdapterView.setPullRefreshEnable(false);
		mAdapterView.setXListViewListener(this);

		mAdapter = new StaggeredAdapter(this, mAdapterView);

		mImageFetcher = new ImageFetcher(this, 220);
		mImageFetcher.setImageCache(new ImageCache(this, "classlist"));
		mImageFetcher.setLoadingImage(R.drawable.empty_photo);

		setSlideMenu();
		setListViewListener();

		if (!KeyFilterUtils.afterTime()) {
			mSelectedClass = 4;
		}

		mAdapterView.setAdapter(mAdapter);
		mAdapterView.startLoadMore();

		DelayTimer();

		MobclickAgent.updateOnlineConfig(PullToRefreshSampleActivity.this);

		initMoreBtn();

		AdManager.getInstance(this).init("be3fd36dfcc43414",
				"532e4c235e70d358", false);
	}

	private void setListViewListener() {
		// TODO Auto-generated method stub
		mAdapterView
				.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(PLA_AdapterView<?> parent,
							View view, int position, long id) {

						DuitangInfo info = mInfos.get(position - 1);
						String sign = info.getSign();

						String url = "http://xiangce.baidu.com/picture/detail/"
								+ sign + "?type=album&format=json";

						Intent intent = new Intent();
						intent.setClass(PullToRefreshSampleActivity.this,
								DetailAblumListActivity.class);

						Bundle bundle = new Bundle();
						bundle.putString("ablum_url", url);
						bundle.putString("pic_sign", sign);
						intent.putExtras(bundle);
						startActivity(intent);
					}

				});
	}

	private void initMoreBtn() {
		Button btn = (Button) findViewById(R.id.more_btn);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(PullToRefreshSampleActivity.this,
						PreferencesSetting.class);

				Bundle bundle = new Bundle();
				intent.putExtras(bundle);
				startActivity(intent);
			}

		});
	}

	public void initAD() {

		RelativeLayout adContainer = (RelativeLayout) findViewById(R.id.adcontainer);

		// Create ad view
		mAdview320x50 = new DomobAdView(this,
				PullToRefreshSampleActivity.PUBLISHER_ID,
				PullToRefreshSampleActivity.FlexPID,
				DomobAdView.INLINE_SIZE_FLEXIBLE);

		mAdview320x50.setKeyword("game");
		mAdview320x50.setUserGender("male");
		mAdview320x50.setUserBirthdayStr("1970-08-08");

		Integer randcode = (int) (Math.random() * 10000000);
		mAdview320x50.setUserPostcode(randcode.toString());

		RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		adContainer.addView(mAdview320x50, layout);

		adContainer.setVisibility(View.VISIBLE);
		mAdview320x50.setVisibility(View.VISIBLE);

		mAdview320x50.setAdEventListener(new DomobAdEventListener() {

			@Override
			public void onDomobAdReturned(DomobAdView adView) {
				Log.i("DomobSDKDemo", "onDomobAdReturned");
			}

			@Override
			public Context onDomobAdRequiresCurrentContext() {
				return PullToRefreshSampleActivity.this;
			}

			@Override
			public void onDomobAdClicked(DomobAdView arg0) {
				// TODO Auto-generated method stub
				MobclickAgent.onEvent(PullToRefreshSampleActivity.this,
						"click", "main_page_ad");
			}

			@Override
			public void onDomobAdFailed(DomobAdView arg0, ErrorCode arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onDomobAdOverlayDismissed(DomobAdView arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onDomobAdOverlayPresented(DomobAdView arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onDomobLeaveApplication(DomobAdView arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

	private void setSlideMenu() {
		// 鍖呭惈TextView鐨凩inearLayout
		LinearLayout menuLinerLayout = (LinearLayout) findViewById(R.id.linearLayoutMenu);
		// 鍙傛暟璁剧疆
		LinearLayout.LayoutParams menuLinerLayoutParames = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, 1);
		menuLinerLayoutParames.gravity = Gravity.CENTER_HORIZONTAL;

		// 娣诲姞TextView鎺т欢
		for (int i = 0; i < mMenus.length; i++) {

			if (!KeyFilterUtils.isCanShow(mMenus[i])) {
				continue;
			}

			TextView tvMenu = new TextView(this);
			tvMenu.setLayoutParams(new LayoutParams(30, 30));
			tvMenu.setPadding(20, 14, 20, 14);
			tvMenu.setText(mMenus[i]);
			tvMenu.setTextColor(Color.WHITE);
			tvMenu.setGravity(Gravity.CENTER_HORIZONTAL);
			tvMenu.setClickable(true);
			tvMenu.setId(i + 1);

			if (i == 0) {
				tvMenu.setBackgroundResource(R.drawable.slidebar);
			}

			tvMenu.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					LinearLayout menuLinerLayout = (LinearLayout) findViewById(R.id.linearLayoutMenu);
					int viewCount = menuLinerLayout.getChildCount();
					for (int j = 0; j < viewCount; ++j) {
						View sv = menuLinerLayout.getChildAt(j);
						sv.setBackgroundColor(0);
					}
					v.setBackgroundResource(R.drawable.slidebar);

					mSelectedClass = v.getId() - 1;
					mInfos.clear();
					currentPage = getSelectedPage();
					mAdapter.notifyDataSetChanged();
					mImageFetcher.setExitTasksEarly(true);
					currentPage--;
					mAdapterView.startLoadMore();

					MobclickAgent.onEvent(PullToRefreshSampleActivity.this,
							"click", "main_page_class_btn");
				}
			});
			menuLinerLayout.addView(tvMenu, menuLinerLayoutParames);
		}
	}

	private int getSelectedPage() {
		Integer page = mReadTmp.get(mSelectedClass);
		if (page == null)
			return 0;
		else
			return page.intValue();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		return true;
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("mainpage");
		MobclickAgent.onResume(this);

	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("mainpage");
		MobclickAgent.onPause(this);
	}

	@Override
	public void onRefresh() {
		mImageFetcher.setExitTasksEarly(false);
		AddItemToContainer(++currentPage, 1);

	}

	@Override
	public void onLoadMore() {
		mImageFetcher.setExitTasksEarly(false);
		AddItemToContainer(++currentPage, 2);

	}

	void DelayTimer() {
		mTimer = new Timer();
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case UPDATE_TEXT:
					/*
					 * 更改UI
					 */
					if (KeyFilterUtils.isShowAD()) {
						initAD();
					}
					mTimer.cancel();
					break;
				}
			}
		};

		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				Log.d("AndroidTimerDemo", "timer");
				mHandler.sendEmptyMessage(UPDATE_TEXT);
				/*
				 * // It doesn't work updating the UI inside a timer. Calendar
				 * cal = Calendar.getInstance();
				 * mButton.setText(cal.toString());
				 */
			}
		};

		mTimer.schedule(mTimerTask, 5000, 1000);
	}

	public void ExitApp() {
		String appName = "是否要退出\""
				+ getResources().getString(R.string.app_name) + "\"?";

		AlertDialog.Builder customBuilder = new AlertDialog.Builder(
				PullToRefreshSampleActivity.this);
		customBuilder.setTitle("提示").setMessage(appName);
		customBuilder.setNegativeButton("否",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		customBuilder.setPositiveButton("是",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});

		customBuilder.setNeutralButton("更多应用",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						DiyManager
								.showRecommendWall(PullToRefreshSampleActivity.this);
					}
				});

		customBuilder.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ExitApp();
			return true;
		}
		return false;
	}

}// end of class
